<template>
  <div class="p16">
    <van-cell-group inset>
      <van-cell title="儿童管理" />
      <van-form @submit="createChild">
        <van-field v-model="childName" name="name" label="姓名" placeholder="输入儿童姓名" clearable />
        <div style="margin: 12px 16px 0 16px">
          <van-button round block type="primary" native-type="submit">新增儿童</van-button>
        </div>
      </van-form>
      <van-cell v-for="c in children.items" :key="c.id" :title="c.name">
        <template #right-icon>
          <van-button size="mini" type="primary" plain @click.stop="openEditDialog(c)">编辑</van-button>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group inset style="margin-top: 16px">
      <van-cell title="事情模板" />
      <van-form @submit="createActivity">
        <van-field v-model="act.title" name="title" label="标题" placeholder="如 老师奖励一次" clearable />
        <van-field v-model.number="act.pointsPerUnit" name="ppu" type="number" label="每次积分" placeholder="可为负数" />
        <van-cell title="支持数量">
          <template #right-icon>
            <input type="checkbox" v-model="act.allowQuantity" />
          </template>
        </van-cell>
        <van-field v-model="act.unitLabel" name="unit" label="单位" placeholder="次/组(可空)" />
        <div style="margin: 12px 16px 0 16px">
          <van-button round block type="primary" native-type="submit">新增模板</van-button>
        </div>
      </van-form>
      <van-cell v-for="t in activityTemplates" :key="t.id"
                :title="t.title"
                :label="`${t.pointsPerUnit} / ${t.allowQuantity ? (t.unitLabel || '次') : '固定'}`">
        <template #right-icon>
          <van-button size="mini" type="danger" plain @click.stop="archiveActivityTemplate(t.id)">删除</van-button>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group inset style="margin-top: 16px">
      <van-cell title="兑换模板" />
      <van-form @submit="createReward">
        <van-field v-model="rew.title" name="rtitle" label="标题" placeholder="如 看电视" clearable />
        <van-field v-model.number="rew.costPoints" name="rcost" type="number" label="消耗积分" placeholder="正整数" />
        <van-field v-model.number="rew.limitPerWeek" name="rlimit" type="number" label="周限额" placeholder="可空" />
        <div style="margin: 12px 16px 0 16px">
          <van-button round block type="primary" native-type="submit">新增兑换项</van-button>
        </div>
      </van-form>
      <van-cell v-for="t in rewardTemplates" :key="t.id"
                :title="t.title"
                :label="t.limitPerWeek ? `消耗 ${t.costPoints} / 周限 ${t.limitPerWeek}` : `消耗 ${t.costPoints}`" />
    </van-cell-group>

    <!-- 编辑儿童弹窗 -->
    <van-popup v-model:show="showEditDialog" round position="bottom" :style="{ height: '70%' }">
      <div style="padding: 16px">
        <h3 style="margin: 0 0 16px 0; text-align: center">编辑儿童信息</h3>
        <van-form @submit="updateChild">
          <van-field v-model="editForm.name" name="name" label="姓名" placeholder="输入儿童姓名" required />

          <van-field
            v-model="editForm.birthdayDisplay"
            name="birthday"
            label="出生日期"
            placeholder="选择出生日期"
            readonly
            @click="showBirthdayPicker = true"
          />

          <van-field v-model.number="editForm.height" name="height" type="number" label="身高 (cm)" placeholder="输入身高" />

          <van-field name="avatar" label="头像">
            <template #input>
              <van-uploader
                v-model="avatarFile"
                :max-count="1"
                :after-read="handleAvatarUpload"
                :preview-image="false"
              >
                <van-button size="small" type="primary">上传头像</van-button>
              </van-uploader>
              <div v-if="editForm.avatarUrl" style="margin-top: 8px">
                <img :src="editForm.avatarUrl" style="width: 80px; height: 80px; border-radius: 8px; object-fit: cover" />
              </div>
            </template>
          </van-field>

          <div style="margin-top: 24px; display: flex; gap: 12px">
            <van-button round block @click="showEditDialog = false">取消</van-button>
            <van-button round block type="primary" native-type="submit">保存</van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showBirthdayPicker" round position="bottom">
      <van-date-picker
        v-model="editForm.birthdayPicker"
        title="选择出生日期"
        :min-date="new Date(2000, 0, 1)"
        :max-date="new Date()"
        @confirm="onBirthdayConfirm"
        @cancel="showBirthdayPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showConfirmDialog, showToast } from 'vant'
import { useChildrenStore } from '@/stores/children'
import dayjs from 'dayjs'

const children = useChildrenStore()
const childName = ref('')
const activityTemplates = ref<any[]>([])
const rewardTemplates = ref<any[]>([])

const act = ref({ title: '', pointsPerUnit: 5, allowQuantity: true, unitLabel: '' })
const rew = ref({ title: '', costPoints: 5, limitPerWeek: undefined as number | undefined })

// 编辑相关状态
const showEditDialog = ref(false)
const showBirthdayPicker = ref(false)
const avatarFile = ref<any[]>([])
const editForm = ref({
  id: 0,
  name: '',
  birthday: null as string | null,
  birthdayDisplay: '',
  birthdayPicker: ['2020', '01', '01'],
  height: undefined as number | undefined,
  avatarUrl: ''
})

async function loadTemplates() {
  const a = await $fetch('/api/activities/templates')
  activityTemplates.value = a.templates
  const r = await $fetch('/api/rewards/templates')
  rewardTemplates.value = r.templates
}

onMounted(async () => {
  await children.load()
  await loadTemplates()
})

async function createChild() {
  if (!childName.value.trim()) return
  await $fetch('/api/children', { method: 'POST', body: { name: childName.value } })
  childName.value = ''
  await children.load()
  showToast('已新增儿童')
}

async function createActivity() {
  if (!act.value.title.trim()) return
  await $fetch('/api/activities/templates', { method: 'POST', body: act.value })
  act.value = { title: '', pointsPerUnit: 5, allowQuantity: true, unitLabel: '' }
  await loadTemplates()
  showToast('已新增事情模板')
}

async function createReward() {
  if (!rew.value.title.trim() || !rew.value.costPoints) return
  const body: any = { title: rew.value.title, costPoints: rew.value.costPoints }
  if (rew.value.limitPerWeek) body.limitPerWeek = rew.value.limitPerWeek
  await $fetch('/api/rewards/templates', { method: 'POST', body })
  rew.value = { title: '', costPoints: 5, limitPerWeek: undefined }
  await loadTemplates()
  showToast('已新增兑换模板')
}

async function archiveActivityTemplate(id: number) {
  try {
    await showConfirmDialog({ title: '确认删除', message: '删除后不可恢复，确定要删除该模板吗？' })
  }
  catch (err) {
    return
  }
  await $fetch(`/api/activities/templates/${id}/archive`, { method: 'POST' })
  await loadTemplates()
  showToast('模板已删除')
}

// 打开编辑弹窗
function openEditDialog(child: any) {
  let pickerValue: [string, string, string] = ['2020', '01', '01']
  if (child.birthday) {
    const date = dayjs(child.birthday)
    pickerValue = [
      date.format('YYYY'),
      date.format('MM'),
      date.format('DD')
    ]
  }
  
  editForm.value = {
    id: child.id,
    name: child.name,
    birthday: child.birthday || null,
    birthdayDisplay: child.birthday ? dayjs(child.birthday).format('YYYY-MM-DD') : '',
    birthdayPicker: pickerValue,
    height: child.height || undefined,
    avatarUrl: child.avatarUrl || ''
  }
  avatarFile.value = []
  showEditDialog.value = true
}

// 日期选择确认
function onBirthdayConfirm() {
  const [year, month, day] = editForm.value.birthdayPicker
  editForm.value.birthday = `${year}-${month}-${day}`
  editForm.value.birthdayDisplay = editForm.value.birthday
  showBirthdayPicker.value = false
}

// 处理头像上传
async function handleAvatarUpload(file: any) {
  const formData = new FormData()
  formData.append('file', file.file)

  try {
    const result = await $fetch('/api/upload/avatar', {
      method: 'POST',
      body: formData
    })
    editForm.value.avatarUrl = result.url
    showToast('头像上传成功')
  } catch (error) {
    showToast('头像上传失败')
    console.error(error)
  }
}

// 更新儿童信息
async function updateChild() {
  if (!editForm.value.name.trim()) {
    showToast('请输入姓名')
    return
  }

  try {
    const body: any = {
      name: editForm.value.name
    }

    if (editForm.value.birthday) {
      body.birthday = editForm.value.birthday
    }

    if (editForm.value.height) {
      body.height = editForm.value.height
    }

    if (editForm.value.avatarUrl) {
      body.avatarUrl = editForm.value.avatarUrl
    }

    await $fetch(`/api/children/${editForm.value.id}`, {
      method: 'PATCH',
      body
    })

    await children.load()
    showEditDialog.value = false
    showToast('儿童信息已更新')
  } catch (error) {
    showToast('更新失败')
    console.error(error)
  }
}
</script>


